import { _decorator, Component, Node, Animation } from 'cc'
import { initParamsNumber, initParamsTrigger, StateMachine } from '../../Base/StateMachine'
import { ENTITY_STATE_ENUM, FSM_PARAMS_TYPE_ENUM, PARAMS_NAME_ENUM } from '../../Enum'
import { DeathSubStateMachineWooden } from '../WoodenSkeleton/DeathSubStateMachineWooden'
import { IdleSubStateMachineDoor } from './IdleSubStateMachineDoor'
import { DeathSubStateMachineDoor } from './DeathSubStateMachineDoor'
const { ccclass, property } = _decorator

/**
 * Predefined variables
 * Name = DoorStateMachine
 * DateTime = Thu Jul 21 2022 20:03:35 GMT+0800 (中国标准时间)
 * Author = Zero_Y
 * FileBasename = DoorStateMachine.ts
 * FileBasenameNoExtension = DoorStateMachine
 * URL = db://assets/Scripts/Door/DoorStateMachine.ts
 * ManualUrl = https://docs.cocos.com/creator/3.4/manual/zh/
 *
 */

@ccclass('DoorStateMachine')
export class DoorStateMachine extends StateMachine {
  resetTrigger() {
    for (const [_, value] of this.params) {
      if (value.type === FSM_PARAMS_TYPE_ENUM.TRIGGER) {
        value.value = false
      }
    }
  }

  // 初始化参数
  initParams() {
    this.params.set(PARAMS_NAME_ENUM.IDLE, initParamsTrigger())
    this.params.set(PARAMS_NAME_ENUM.DIRECTION, initParamsNumber())
    this.params.set(PARAMS_NAME_ENUM.DEATH, initParamsTrigger())
  }

  // 初始化状态机
  initStateMachine() {
    // 门初始化
    this.stateMachines.set(PARAMS_NAME_ENUM.IDLE, new IdleSubStateMachineDoor(this))
    // 门消失
    this.stateMachines.set(PARAMS_NAME_ENUM.DEATH, new DeathSubStateMachineDoor(this))
  }

  // 初始化动画
  initAnimationEvent() {}

  async init() {
    // 添加动画组件
    this.animationComponent = this.addComponent(Animation)
    this.initParams()
    this.initStateMachine()
    this.initAnimationEvent()
    // 确保资源资源加载
    await Promise.all(this.waitingList)
  }
  run() {
    switch (this.currentState) {
      case this.stateMachines.get(PARAMS_NAME_ENUM.IDLE):
      case this.stateMachines.get(PARAMS_NAME_ENUM.DEATH):
        if (this.params.get(PARAMS_NAME_ENUM.DEATH).value) {
          this.currentState = this.stateMachines.get(PARAMS_NAME_ENUM.DEATH)
        } else if (this.params.get(PARAMS_NAME_ENUM.IDLE).value) {
          this.currentState = this.stateMachines.get(PARAMS_NAME_ENUM.IDLE)
        } else {
          // 为了触发子状态机的改变
          this.currentState = this.currentState
        }
        break
      default:
        this.currentState = this.stateMachines.get(PARAMS_NAME_ENUM.IDLE)
    }
  }
}
